require('whatwg-fetch');
const fetchJsonp = require('fetch-jsonp');
import { HOST } from 'root_path/constants/constant.js';
function getParam(data){
    let paramStr = "";
    for(let key in data){
        paramStr += key+'='+data[key]+"&";
    }
    return paramStr.substr(0, paramStr.length-1);
}
//CORS POST提交数据
export function postData(params) {
    let { path, data } = params;
    let url = HOST+path;
    return new Promise((resolve, reject)=>{
        fetch(url, {
            body: JSON.stringify(data), // must match 'Content-Type' header
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, same-origin, *omit
            headers: {
                'user-agent': 'Mozilla/4.0 MDN Example',
                'content-type': 'application/json'
            },
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            mode: 'cors', // no-cors, cors, *same-origin
            redirect: 'follow', // manual, *follow, error
            referrer: 'no-referrer', // *client, no-referrer
        }).then(response => response.json())
        .then((json) =>{
            if(json.status.code===1){
                resolve(json.result);
            }else{
                console.error(json.status.msg);
                reject(json.status);
            }
        }).catch(function(err) {
            console.log(err);
        });
    });
}
//Jsonp get提交数据
export function getData(params){
    let { path, data } = params;
    let paramStr = getParam(data);
    const url = HOST+path+"?"+paramStr;
    return new Promise((resolve, reject)=>{
        fetchJsonp(url, {credentials: "include", timeout: 10000})
        .then( response=>response.json() )
        .then((json) =>{
            if(json.status.code===1){
                resolve(json.result);
            }else{
                console.error(json.status.msg);
                reject(json.status);
            }
         }).catch(function(err) {
            console.log(err);
        })
    });
  }


//Jsonp get提交数据
export function httpGet(params){
    let { path, data } = params;
    let paramStr = getParam(data);
    const url = HOST+path+"?"+paramStr;
    return new Promise((resolve, reject)=>{
        fetch(url, {method:"GET"})
        .then(res=>res.json())
        .then((json)=>{
            if(json.status.code===1){
                resolve(json.result);
            }else{
                console.error(json.status.msg);
                reject(json);
            }
        }).catch((err)=>{
            console.log(err);
        });
    });
  }